package com.rogchen.security.securitycustomuser.configuration;

import com.rogchen.security.securitycustomuser.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author Rogchen rogchen128@gmail.com
 * @description:
 * @product: IntelliJ IDEA
 * @created Date: 19-11-6 14:42
 **/
@Component("authenticationProvider")
public class SecurityAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private CustomUserService customUserService;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        BCryptPasswordEncoder cy = new BCryptPasswordEncoder();
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        SysUserVo vo = customUserService.loadUserByUsername(username);
        if (vo == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        //匹配规则是将未的密码跟已经加密后的匹配
        if (!cy.matches(password, vo.getPassword())) {
            throw new BadCredentialsException("密码不正确！");
        }
        //根据用户获取权限 放入authorities中去
        Collection<? extends GrantedAuthority> authorities = vo.getAuthorities();
        return new UsernamePasswordAuthenticationToken(vo, password, authorities);// 构建返回的用户登录成功的token
    }

    /**
     * 执行支持判断
     *
     * @param authentication
     * @return
     */
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
